package com.gqr.flowcontrol.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:CountDownLatchDemo2
 * author:guqingrong
 * Date:2024-05-16 21:34
 * Description:模拟100米跑步,5名选手都准备好了,只等裁判员一声令下,所有人同时开始跑步
 * 当所有人都到终点后,比赛结束
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class CountDownLatchDemo2 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch begin = new CountDownLatch(1); // 发令枪
        CountDownLatch end = new CountDownLatch(5); // 终点裁判收到5次信号代表所有运动员都完成了
        ExecutorService service = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 5; i++) {
            final int no = i + 1;
            Runnable r = new Runnable() {

                @Override
                public void run() {
                    System.out.println("No." + no + "准备完毕,等待发令枪");
                    try {
                        begin.await();
                        System.out.println("No." + no + "开始跑步");
                        Thread.sleep((long) (Math.random() * 10000));
                        System.out.println("No." + no + "跑到终点了");

                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }finally {
                        end.countDown();
                    }
                }
            };

            service.submit(r);
        }
        // 裁判员检查等待...
        Thread.sleep(5000);
        System.out.println("发令枪响,比赛开始1");
        begin.countDown();
        // 等待5个线程执行完
        end.await();
        System.out.println("所有人到达重点,比赛结束");
    }
}
